<?php
namespace app\attachment\controller;

use app\attachment\model\Attachment;

class Upload extends Base
{
    protected $model;

    protected function initialize()
    {
        parent::initialize();
        $this->model = Attachment::getInstance();
    }


    /**
     * 上传图片
     * 地址： attachment/Home/uploadImage
     * @return array
     */
    public function uploadImage()
    {
        //获取上传的文件
        $filelist = $this->request->file();
        $file = reset($filelist);

        //获取待上传文件的信息
        $fileinfo = $file->getInfo();
        $ext = $this->getExt($fileinfo['name']);
        //计算文件大小是否超过限制
        if (!$this->checkFileSize($fileinfo['size'], $ext)) {
            return ['code' => 0, 'msg' => $this->getError()];
        }
        //计算待上传文件的MD5值，为了对比数据库是否已有此值，可避免重复上传，并且可以闪电上传
        $md5 = md5_file($fileinfo['tmp_name']);
        //根据MD5值获取信息，查找数据库中是否已有文件
        $att_info = $this->model->getOne(['md5' => $md5]);
        //初始化不需要上传文件   OSS文件是否存在,初始化为不存在
        $is_upload = $oss_file_exist = 0;
        $filename = '';


        $upload_path = $this->getUploadPath($this->userid);
        $info = $file->move($upload_path);
        if (!$info) {
            // 上传失败获取错误信息
            return array2json(['code' => 0, 'msg' => '上传文件失败']);
        }
        if (empty($att_info)) {
            //写入到附件表
            $data = [];
            $data['qiniu_url'] = $filename;
            //模块
            $data['module'] = 'home';
            //文件名
            $data['filename'] = $fileinfo['name'];
            //文件路径
            $data['filepath'] = $filename;
            //文件后缀
            $data['fileext'] = $ext;
            //文件大小
            $data['filesize'] = $fileinfo['size'];
            //文件MD5值
            $data['md5'] = $md5;
            $data['qpic_url'] = '';
        } else {
            $data = $att_info;
            $data['qiniu_url'] = $filename;
            unset($att_info, $data['id']);
        }
        //查询是否是本人上传
        $data['user_id'] = isset($this->userid) ? $this->userid : 0;
        $data['uploadip'] = $this->request->ip();
        $data['cateid'] = $this->upload_platform;
        $data['create_time'] = time();
        $data['status'] = 1;
        $qiniu_url = false === strpos($data['qiniu_url'], 'http') ? $this->base_url . $data['qiniu_url'] : $data['qiniu_url'];
        $data['md5_url'] = md5(trim($qiniu_url));
        $aid = $this->model->addData($data);
        if (false === $aid) {
            return ['code' => 0, 'msg' => $this->model->getError()];
        } else {
            return ['code' => 1, 'pic' => $qiniu_url, 'id' => $aid, 'name' => $data['filename']];
        }
    }


    /**
     * 批量上传图片
     * 地址： attachment/Home/uploadImages
     * @return array
     */
    public function uploadImages()
    {
        if ($this->userid < 1) {
            return ['code' => 0, 'msg' => '您未登录'];
        }
        //获取上传的文件
        $filelist = $this->request->file();
        //判断是否需要打水印
        $is_water = $this->getWaterInfo($this->userinfo);
        //上传文件列表
        $file_array = [];
        //实例化上传类
        $upload_class = $this->upload_platform == 0 ? new Qiniu() : new Oss();
        foreach ($filelist as $k => $item) {
            //获取待上传文件的信息
            $fileinfo = $item->getInfo();
            $ext = $this->getExt($fileinfo['name']);
            //计算文件大小是否超过限制
            if (!$this->checkFileSize($fileinfo['size'], $ext)) {
                return ['code' => 0, 'msg' => $this->getError()];
            }
            //计算待上传文件的MD5值，为了对比数据库是否已有此值，可避免重复上传，并且可以闪电上传
            $md5 = md5_file($fileinfo['tmp_name']);
            //初始化不需要上传文件   OSS文件是否存在,初始化为不存在
            $is_upload = $oss_file_exist = 0;
            $filename = '';
            //根据MD5值获取信息，查找数据库中是否已有文件
            $att_info = $this->model->getOne(['md5' => $md5]);

            if (empty($att_info)) {
                $is_upload = 1;
            } else {
                //获取文件信息，如果不存在，则需要重新上传
                $filename = $att_info['qiniu_url'];
                $image_info = $upload_class->getFileMeta($att_info['qiniu_url']);
                if (empty($image_info)) {
                    $is_upload = 1;
                } else {
                    $oss_file_exist = 1;
                }
            }
            //上传图片
            if ($is_upload == 1) {
                //新上传需要一个新名字，
                $filename = $this->getUploadPath($this->userid, false) . date('Ymd') . '/' . uniqid() . random(10, 'letter', 1) . '.' . $ext;
                //上传文件
                if (!$upload_class->upload($filename, $fileinfo['tmp_name'])) {
                    return $this->error($upload_class->getError());
                }
            }
            /**
             * GIF图片不能打水印及其他处理
             * $local_file  本地图片需要上传到微信服务器
             */
            $local_file = SITE_PATH . $filename;
            if ($ext != 'gif') {
                $options = $is_water ? $upload_class->watermark($filename, $this->userinfo) : [];
                //当本地图片不存在时需要下载
                if (!is_file($local_file)) {
                    $upload_class->downloadFile($filename, $local_file, $options);
                }
                //当OSS上不存在此文件，或者需要打水印时，则需要重新上传图片
                if ($oss_file_exist == 0 || $options) {
                    $filename = str_replace('.', 'thumb.', $filename);
                    if (!$upload_class->upload($filename, $local_file)) {
                        return ['state' => $upload_class->getError()];
                    }
                }
            }
            if (empty($att_info)) {
                //写入到附件表
                $data = [];
                $data['qiniu_url'] = $filename;
                //模块
                $data['module'] = 'ueditor';
                //文件名
                $data['filename'] = $fileinfo['name'];
                //文件路径
                $data['filepath'] = $filename;
                //文件后缀
                $data['fileext'] = $ext;
                //文件大小
                $data['filesize'] = $fileinfo['size'];
                //文件MD5值
                $data['md5'] = $md5;
                $data['qpic_url'] = '';
            } else {
                $data = $att_info;
                $data['qiniu_url'] = $filename;
                unset($att_info, $data['id']);
            }

            //查询是否是本人上传
            $data['user_id'] = isset($this->userid) ? $this->userid : 0;
            $data['uploadip'] = $this->request->ip();
            $data['cateid'] = $this->upload_platform;
            $data['create_time'] = time();
            $data['status'] = 1;
            $qiniu_url = false === strpos($data['qiniu_url'], 'http') ? $this->base_url . $data['qiniu_url'] : $data['qiniu_url'];
            $data['md5_url'] = md5(trim($qiniu_url));
            //获取腾讯图片
            if (empty($data['qpic_url'])) {
                //在上传的过程中$filename可能已改变
                $qpic = $this->getQpic(str_replace(SITE_PATH, '', $local_file));
                if ($qpic) {
                    $data['qpic_url'] = $qpic;
                    $data['sync_pic_type'] = 1;
                    $data['is_sync'] = 0;
                }
            }
            $data['id'] = heartbeat('attachment');
            //添加到数组中
            $add_id = $this->model->addData($data);
            if ($add_id) {
                $file_array[] = ['id' => $add_id, 'filename' => $filename];
            }
            unset($this->model->id);
        }
        if (empty($file_array)) {
            return json(['code' => 0, 'msg' => $this->model->getError()]);
        } else {
            return json(['code' => 1, 'filelist' => $file_array]);
        }
    }


    /*
     * 获取文件后缀
     * */
    public function getType($file)
    {
        if (!$file) {
            return false;
        }
        $arr = explode('.', $file);
        return array_pop($arr);
    }


    /**
     * base64格式图片上传，主要用于网站右侧的上传
     * @param $imgString   图片BASE64码
     * @param int $gid 分组ID
     * @return array
     */
    public function baseImage($imgString, $gid = 0)
    {
        if (empty($imgString)) {
            return ['state' => '图片不能为空'];
        }
        $number = preg_match('/^(data:\s*image\/(\w+);base64,)/', $imgString, $result);
        if ($number == 0) {
            return ['state' => '非法格式'];
        }
        //图片格式
        $ext = $result[2];
        //文件内容
        $file_content = file_get_contents($imgString);
        $file_len = strlen($file_content);
        //计算文件大小是否超过限制
        if (!$this->checkFileSize($file_len, $ext)) {
            return ['state' => $this->getError()];
        }
        //文件路径名
        $file = $this->getUploadPath($this->userid) . date('Ymd', time()) . '/' . md5(time() . random(10, 'letter', 1)) . '.' . $ext;
        $filename = str_replace(SITE_PATH, '', $file);
        //上传到OSS


        $upload_class = new Oss();
        $res = $upload_class->putFile($filename, $file_content);

        if (!$res) {
            return ['state' => $upload_class->getError()];
        }
        if ($ext != 'gif') {
            //打水印
            $options = $upload_class->watermark($filename, $this->userinfo);
            //下载图片规则处理后的图片
            $upload_class->downloadFile($filename, $file, $options);
            $filename = str_replace('.', 'thumb.', $filename);
            //重新上传到网络并且覆盖原图
            $upload_class->upload($filename, $file);
        }

        //写入到附件表
        $data = [];
        //模块
        $data['module'] = 'home';
        //文件名
        $data['filename'] = $filename;
        //文件路径
        $data['filepath'] = $filename;
        //文件后缀
        $data['fileext'] = $ext;
        //文件大小
        $data['filesize'] = $file_len;
        //文件MD5值
        $data['md5'] = md5($file_content);
        //文件内容的md5值
        $data['md5_base'] = md5($file_content);
        //七牛文件名
        $data['qiniu_url'] = $filename;
        //查询是否是本人上传
        $data['user_id'] = $this->userid;
        $data['uploadip'] = $this->request->ip();
        $data['cateid'] = $this->upload_platform;
        $data['status'] = 1;
        $data['grouping_id'] = $gid;
        $data['create_time'] = time();
        $qiniu_url = false === strpos($data['qiniu_url'], 'http') ? $this->base_url . $data['qiniu_url'] : $data['qiniu_url'];
        $data['md5_url'] = md5(trim($qiniu_url));
        //获取腾讯图片
        $qpic = $this->getQpic(str_replace(SITE_PATH, '', $file));
        if ($qpic) {
            $data['qpic_url'] = $qpic;
            $data['sync_pic_type'] = 1;
            $data['is_sync'] = 0;
        }
        $aid = $this->model->addData($data);
        if (false === $aid) {
            return ['state' => '写入数据失败'];
        } else {
            return [
                'state' => 'SUCCESS',
                'url' => $qiniu_url,
                'title' => $filename,
                'original' => $filename,
                'id' => $aid,
                'type' => $ext,
                'size' => $data['filesize'],
            ];
        }
    }

    /**
     * 上传图片
     * 地址： attachment/Home/uploadImage
     * @return array
     */
    public function uploadCloud($filename, $file_path, $userid = 0)
    {
        if ($userid < 1) {
            $this->error = '您还未登录';
            return false;
        }
        //上传到云存储
        $result = $this->cloudStorage($filename, $file_path, $userid);
        if (!$result) {
            $this->error = '上传到云存储失败';
            return false;
        }
        return $this->base_url . $filename;
    }

    /**
     * 上传界面
     * @return mixed
     */
    public function image()
    {
        $post = $this->request->param();
        $ext = isset($post['ext']) ? $post['ext'] : 'jpg|jpeg|gif|png|bmp';//后缀，默认只能上传图片
        $info['ext'] = str_replace('|', ',', $ext);
        $info['name'] = $post['name'];
        $info['path_name'] = $this->upload_dir;
        $this->assign($info);
        return $this->fetch();
    }


}
